package com.zgys.mes.common.config.datasource;

import javax.sql.DataSource;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;


@Configuration
@MapperScan(basePackages = "com.zgys.mes.dao.mapper",
            sqlSessionFactoryRef = "mesSqlSessionFactory")
public class MesDataSourceConfig {
    static final String MAPPER_LOCATION = "classpath:sql/*.xml";
//    static final String CONFIG_LOCATION = "classpath:mybatis.xml";
    static final String DaoDir = "com.zgys.mes.dao.mapper";

    @Value("${spring.datasource.driver-class-name}") String driver;
    @Value("${spring.datasource.url}") String url;
    @Value("${spring.datasource.username}") String username;
    @Value("${spring.datasource.password}") String password;


    @Bean(name = "mesDataSource")
    @Primary
    public DataSource mesDataSource() {

        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(driver);
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);

        return druidDataSource;
    }


    @Bean(name = "mesTransactionManager")
    @Primary
    public DataSourceTransactionManager mesTransactionManager() {
        return new DataSourceTransactionManager(mesDataSource());
    }


    @Bean(name = "mesSqlSessionFactory")
    @Primary
    public SqlSessionFactory mesSqlSessionFactory(@Qualifier("mesDataSource") DataSource mesDataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(mesDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(MesDataSourceConfig.MAPPER_LOCATION));
        sessionFactory.setTypeAliasesPackage(DaoDir);

        //        Resource r = new PathMatchingResourcePatternResolver().getResource(CONFIG_LOCATION);
//        sessionFactory.setConfigLocation(r);
        return sessionFactory.getObject();
    }


    @Bean(name = "SqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(
            @Qualifier("mesSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}

